package com.well.rpc.handler;

import com.well.rpc.event.AppEvent;
import com.well.rpc.event.EventContext;
import com.well.rpc.event.ExceptionEvent;
import com.well.rpc.model.EventType;
import com.well.rpc.model.TransData;
import com.well.rpc.utils.ThreadPoolUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import com.well.rpc.config.ClientDataConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 处理客户端响应数据
 */
public class ClientEventHandler extends SimpleChannelInboundHandler<TransData> {
    Logger logger = LoggerFactory.getLogger(ClientEventHandler.class);
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");

    /**
     * 处理连接有效事件
     * @param ctx 上下文
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ClientHandler.setChannelContext(ctx);
        if (!ClientDataConfig.getClientRegisterStatus()) {
            ClientHandler.initClient();
        }
    }

    /**
     * 读取channel中的数据
     * @param channelHandlerContext channel上下文
     * @param transData 接收数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TransData transData) {
        AppEvent eventByType = null;
        try {
            EventType type = transData.getType();
            eventByType = EventContext.getEventByType(type);
            if (eventByType == null) {
                logger.error("Wrong Client Event !");
                return;
            }
            AppEvent finalEventByType = eventByType;
            ThreadPoolUtils.execute(() -> {
                finalEventByType.doEvent(channelHandlerContext, transData);
            });
        } catch (Exception e) {
            assert eventByType != null;
            eventByType.errorEvent(channelHandlerContext, e);
        }
    }

    /**
     * 处理器处理心跳事件
     * @param ctx 上下文
     * @param evt event
     * @throws Exception e
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                ClientHandler.heartBeat();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        logger.info("Server DisConnected,time ：" + format.format(new Date()));
        ExceptionEvent exceptionEvent = (ExceptionEvent) EventContext.getEventByType(EventType.EXCEPTION);
        exceptionEvent.doChannelInactive();
    }

}
